package com.gitee.helioz.openai.api.endpoint.files;

import com.gitee.helioz.openai.api.OpenAiService;
import com.gitee.helioz.openai.api.dto.files.FileDTO;
import com.gitee.helioz.openai.api.dto.DeleteResponse;
import com.gitee.helioz.openai.api.dto.files.FileResponse;
import com.gitee.helioz.openai.api.dto.files.FileUploadRequest;
import com.gitee.helioz.openai.common.constants.OpenAiApiUrl;
import com.gitee.helioz.openai.common.util.BeanUtil;
import com.gitee.helioz.openai.common.util.http.HttpFilePart;
import com.gitee.helioz.openai.common.util.json.GsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 〈文件服务〉
 *
 * @author <a href="https://gitee.com/helioz">Morning Starr</a>
 */
@Slf4j
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final OpenAiService openAiService;

    @Override
    public FileResponse list() {
        String responseStr = openAiService.get(OpenAiApiUrl.Files.LIST.getUrl(openAiService.getApiHost()));
        return GsonUtil.fromJson(responseStr, FileResponse.class);
    }

    @Override
    public FileDTO upload(FileUploadRequest fileRequest) {
        String requestJson = GsonUtil.toJson(fileRequest);
        log.debug("上传文件，请求={}", requestJson);
        Map<String, Object> formMap = BeanUtil.beanToMap(fileRequest, "file");
        List<HttpFilePart> fileParts = new ArrayList<>(3);
        HttpFilePart file = fileRequest.getFile();
        if (file != null) {
            file.setPartName("file");
            fileParts.add(file);
        }
        String responseStr = openAiService.postFormData(OpenAiApiUrl.Files.UPLOAD.getUrl(openAiService.getApiHost()), formMap, fileParts);
        return GsonUtil.fromJson(responseStr, FileDTO.class);
    }

    @Override
    public DeleteResponse delete(String fileId) {
        String responseStr = openAiService.delete(OpenAiApiUrl.Files.DELETE.getUrl(openAiService.getApiHost()) + fileId);
        return GsonUtil.fromJson(responseStr, DeleteResponse.class);
    }

    @Override
    public FileDTO retrieve(String fileId) {
        String responseStr = openAiService.get(OpenAiApiUrl.Files.RETRIEVE.getUrl(openAiService.getApiHost()) + fileId);
        return GsonUtil.fromJson(responseStr, FileDTO.class);
    }

    @Override
    public String retrieveContent(String fileId) {
        String responseStr = openAiService.get(String.format(OpenAiApiUrl.Files.RETRIEVE_CONTENT_FORMAT.getUrl(openAiService.getApiHost()), fileId));
        return responseStr;
    }
}
